var util = require("../util");

module.exports = function(e) {
    var t = [], n = util.reWriteMethod, o = {
        consoleBehavior: function() {
            if (console) {
                var e = [ "debug", "info", "warn", "log", "error" ], t = null;
                if (Function && (t = Function.prototype.apply || Function.apply), "function" == typeof t) for (var o = this, r = 0; r < e.length; r++) {
                    var i = e[r];
                    "function" == typeof console[i] && n(console, i, function(e) {
                        var n = i;
                        return function() {
                            for (var r = arguments.length, i = new Array(r), a = 0; a < r; a++) i[a] = arguments[a];
                            var s = {
                                type: "console",
                                data: {
                                    level: n,
                                    message: i
                                }
                            };
                            o && "function" == typeof o.addBehavior && o.addBehavior(s), "function" == typeof e && t.call(e, console, i);
                        };
                    });
                }
            }
        }
    };
    return util.ext(e.prototype, {
        addBehavior: function(e) {
            if (this.getConfig("behavior") && e && "object" == typeof e) {
                var n = "";
                this._conf && "function" == typeof this._conf.getCurrentPage && (n = this._conf.getCurrentPage());
                var o = null;
                try {
                    o = Date.now();
                } catch (s) {
                    return void util.warn("[arms] error in Date.now", s);
                }
                var r = {}, i = e.data || {};
                if (e.type) r = i; else {
                    if ("string" != typeof i.name || "string" != typeof i.message) return;
                    r.name = i.name.substr(0, 20), r.message = i.message.substr(0, 200);
                }
                r.message && (r.message = util.encode(r.message));
                var a = {
                    type: e.type || "custom",
                    data: r || {},
                    timestamp: e.timestamp || o,
                    page: e.page || n
                };
                return t.push(a), t = t.slice(-100);
            }
        },
        getBehavior: function() {
            return t || [];
        },
        setBehavior: function(e) {
            return e && (t = e), t;
        },
        reportBehavior: function() {
            var e = this;
            e.getConfig("behavior") && (e.sendBhTimer && (clearTimeout(e.sendBhTimer), e.sendBhTimer = undefined), 
            e.sendBhTimer = setTimeout(function() {
                t && t.length > 0 && ("function" == typeof e.behavior && e.behavior(t), t = []);
            }, 0));
        },
        initBehavior: function() {}
    }), o;
};